package com.minshenglife.zanzan.pub.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class AesSecretTool {
	/**
	 * AES 加密
	 * @param str
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String AesEncrypt(String str, String key) throws Exception {
        if (str == null || key == null) return null;
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
        byte[] bytes = cipher.doFinal(str.getBytes("utf-8"));
        return new BASE64Encoder().encode(bytes);
    }
	/**
	 * AES 解密
	 * @param str
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String AesDecrypt(String str, String key) throws Exception {
		if (str == null || key == null){
			return null;
		}
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key
				.getBytes("utf-8"), "AES"));
		byte[] bytes = new BASE64Decoder().decodeBuffer(str);
		bytes = cipher.doFinal(bytes);
		return new String(bytes, "utf-8");
	}
	
	public static void main(String[] args) throws Exception {
		String aStr = AesEncrypt("", "");
		System.out.println(aStr);
		String str = AesDecrypt("", "");
		System.out.println(str);
	}
}
